<!DOCTYPE html>
<html class="x-admin-sm">

<head>
  <meta charset="UTF-8">
  <title>人员导表</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <link rel="stylesheet" href="../../css/font.css">
  <link rel="stylesheet" href="../../css/xadmin.css">
  <link rel="stylesheet" href="../../lib/layui/css/layui.css">

  <script src="../../js/jquery.min.js" type="text/javascript" charset="utf-8"></script>
  <script src="../../js/app.js" type="text/javascript" charset="utf-8"></script>
  <style type="text/css">
    .form-position {
      margin: 0.85rem;
      padding-top: 8px;
      background-color: white;
    }
  </style>
</head>

<body>
  <div class="x-nav">
    <span class="layui-breadcrumb">
      <a href="">首页</a>
      <a href="">演示</a>
      <a>
        <cite>导航元素</cite></a>
    </span>
    <a class="layui-btn layui-btn-small" style="line-height:1.6em;margin-top:3px;float:right"
      onclick="location.reload()" title="刷新">
      <i class="layui-icon layui-icon-refresh" style="line-height:30px"></i></a>
  </div>
  <div class="layui-fluid">
    <div class="layui-row layui-col-space15">
      <div class="layui-col-md12">
        <div class="layui-card">
          <div class="layui-card-body ">
            <blockquote class="layui-elem-quote" style="margin-top: 10px; width: 97%;">
              <a href="http://47.94.20.119:8080/inventory_development/static/人员导表样表.xlsx">下载样表</a>
            </blockquote>

            <div class="layui-collapse" lay-filter="test">
              <div class="layui-colla-item">

                <!--  -->
                <!--  -->
                <h2 class="layui-colla-title">选择Excel表格入库<i class="layui-icon layui-colla-icon"></i></h2>
                <div class="layui-colla-content" style="display:flex;">

                  <div class="layui-inline layui-show-xs-block" style="margin-top: 7.2px;margin-left: 4px;">
                    <input type="file" id='inputfilename'>
                  </div>
                  <div class="layui-inline layui-show-xs-block" style="margin-top: 7.2px;margin-left: 10px;">
                    <button class="layui-btn layui-btn-normal" onclick="readWorkbookFromLocalFile()">读取Excel表格</button>
                  </div>

                  <form class="layui-form layui-hide" id="FORM">
                    <div class="layui-form-item" style="margin: 8px">
                      <div class="layui-input-inline">
                        <select name="usertype" id="usertype" lay-verify="required" lay-search="">
                          <option value="">选择员工类型</option>
                          <!-- 用户归属列表数据区域 -->
                        </select>
                      </div>
                    </div>
                  </form>

                  <div id="buttons" class="layui-hide layui-inline">
                    <div class="layui-inline layui-show-xs-block" style="margin-top: 7.2px;margin-left: 10px;">
                      <button class="layui-btn" onclick="addUserByExcel_Ajax('2');">导入市级员工库</button>
                    </div>
                    <div class="layui-inline layui-show-xs-block" style="margin-top: 7.2px;margin-left: 10px;">
                      <button class="layui-btn" onclick="addUserByExcel_Ajax('1');">导入县级员工库</button>
                    </div>
                    <div class="layui-inline layui-show-xs-block" style="margin-top: 7.2px;margin-left: 10px;">
                      <button class="layui-btn" onclick="addUserByExcel_Ajax('0');">导入普通员工库</button>
                    </div>
                  </div>

                </div>
                <div id="result"></div> 
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 使用lay-ui的表单控件 -->
    <script type="text/javascript" src="../../lib/layui/layui.js" charset="utf-8"></script>
    <!-- 从data.js中获取用户归属列表数据区域 -->
    <script src="./user-data.js"></script>
    <!-- 导表入库 -->
    <script src="../../js/xlsx.core.min.js"></script>
    <script>
      layui.use(['form', 'layer'], function () {
        var form = layui.form,
          layer = layui.layer;
      });
      var usertype = $('#usertype');
      usertype.append(opitons);
      // console.log(opitons); 

      // 创造workbook对象
      var json = null;

      function readWorkbookFromLocalFile() {
        // var files = document.getElementById('inputfilename');
        // console.log(files[0]);
        
        var file = document.getElementById('inputfilename').files[0];
        // console.log(file);
        if (file) {
          var reader = new FileReader();

          reader.onload = function (e) {
            // console.log(e);
            
            var data = e.target.result;
            var workbook = XLSX.read(data, {
              type: 'binary'
            });
            readWorkbook(workbook);
          };
          reader.readAsBinaryString(file);

          $('#FORM').removeClass('layui-hide');
          $('#buttons').removeClass('layui-hide');
        } else {
          layer.msg('请先选择文件')
        }
      }

      // 将excel内容转换为csv和json
      var csv = '';

      function readWorkbook(workbook) {
        var sheetNames = workbook.SheetNames; // 工作表名称集合
        var worksheet = workbook.Sheets[sheetNames[0]]; // 这里我们只读取第一张sheet的内容

        csv = XLSX.utils.sheet_to_csv(worksheet);
        document.getElementById('result').innerHTML = csv2table(csv);

        json = XLSX.utils.sheet_to_json(worksheet);
        // console.log(json);

        for (var i in json) {
          for (var key in json[i]) {
            if (key == '年龄') {
              json[i]['age'] = json[i][key] //修改属性名为“age”
              delete json[i]['年龄'] //删除“年龄”
            } else if (key == '密码') {
              json[i]['password'] = json[i][key] + ''; //修改属性名为“password”
              delete json[i]['密码'] //删除“密码”
            } else if (key == '身份证号码') {
              json[i]['id'] = json[i][key] + ''; //修改属性名为“id”
              delete json[i]['身份证号码'] //删除“身份证号码”
            } else if (key == '性别') {
              if (json[i][key] == '男') {
                json[i][key] = '1';
              } else {
                json[i][key] = '0';
              }
              json[i]['sex'] = json[i][key] //修改属性名为“sex”
              delete json[i]['性别'] //删除“性别”
            } else if (key == '姓名') {
              json[i]['username'] = json[i][key] //修改属性名为“username”
              delete json[i]['姓名'] //删除“姓名”
            } else if (key == '工号') {
              json[i]['workId'] = json[i][key] + ''; //修改属性名为“workId”
              delete json[i]['工号'] //删除“工号”
            }
          }
        }
        // console.log(json);

      }

      // 将csv转换成简单的表格，会忽略单元格合并，在第一行和第一列追加类似excel的索引
      function csv2table(csv) {
        console.log(csv);
        
        var html = '<table class="layui-table layui-form">';
        var rows = csv.split('\n');
        rows.pop(); // 最后一行没用的
        rows.forEach(function (row, idx) {
          var columns = row.split(',');
          columns.unshift(idx + 1); // 添加行索引
          if (idx == 0) { // 添加列索引
            html += '<tr>';
            for (var i = 0; i < columns.length; i++) {
              html += '<th>' + (i == 0 ? '' : String.fromCharCode(65 + i - 1)) + '</th>';
            }
            html += '</tr>';
          }
          html += '<tr>';
          columns.forEach(function (column) {
            html += '<td>' + column + '</td>';
          });
          html += '</tr>';
        });
        html += '</table>';
        return html;
      }


      var info = app.getManagerGlobalInfo();
      // console.log(info)

      // 将人员入库
      function addUserByExcel_Ajax(type) {
        var managerId = app.getManagerId();
        // console.log(managerId);
        var roleId = $('#usertype option:selected').val();
        if (!roleId) {
          layer.msg('请先选择人员类型！')
        } else {
          var typeMsg = '';
          if (type == '2') {
            typeMsg = '确认要导入市级员工库吗？'
          } else if (type == '1') {
            typeMsg = '确认要导入县级员工库吗？'
          } else {
            typeMsg = '确认要导入普通员工库吗？'
          }
          layer.confirm(typeMsg, {
            icon: 3,
            title: '提示信息',
            btn: ['确定', '取消'],
            yes: function () {
              $.ajax({
                url: app.ServerUrl + 'v1/user/addUserByExcel',
                type: "POST",
                contentType: "application/json;charset=UTF-8",
                dataType: "json",
                async: true,
                headers: {
                  "Authorization": info.sessionId
                },
                data: JSON.stringify({
                  "managerId": managerId,
                  "roleId": roleId,
                  "type": type,
                  "userBoSonList": json
                }),
                beforeSend: function(){
                  loading = layer.load();
                },
                success: function (data) {
                  // console.log(data);
                  layer.close(loading);
                  if (data.resultStatus === -1) {
                    if (data.objs != null) {
                      var ExistingWorkIdmsg = data.resultIns + '。\t已存在的工号有：';
                      ExistingWorkIdmsg += data.objs[0];
                      layer.alert(ExistingWorkIdmsg, {
                          icon: 0
                        },
                        function (index) {
                          layer.close(index);
                        });
                    } else {
                      layer.open({
                        content: data.resultIns,
                        btnAlign: 'r',
                        anim: 5,
                        icon: 7,
                        cancel: function () {},
                        yes: function () {
                          // window.location.reload();
                        }
                      })
                    }
                  } else {
                    layer.open({
                      content: '导入成功',
                      btnAlign: 'c',
                      anim: 5,
                      icon: 6,
                      yes: function () {
                        window.location.reload();
                      }
                    })
                  }
                },
                error: function (data) {
                  layer.open({
                    content: '导入失败',
                    btnAlign: 'c',
                    anim: 5,
                    icon: 5,
                    cancel: function () {},
                    yes: function () {
                      window.location.reload();
                    }
                  })
                }
              })
            },
            cancel: function () {

            }
          })



        }

      }

      var _hmt = _hmt || [];
      (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?b393d153aeb26b46e9431fabaf0f6190";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
      })();
    </script>
    <script type="text/javascript" src="../../js/xadmin.js"></script>
</body>

</html>